
// 产品模块
const sequelize = require('../config/operateDB');
const { Sequelize, DataTypes, Op } = require('sequelize');
const { User } = require('./users');
const session = require('koa-session');


const News = sequelize.define('news', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    title: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    content: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    // 0: 
    type: {
        type: DataTypes.INTEGER,
        allowNull: false,
    },
    commentNumber: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
    },
    img: {
        type: DataTypes.STRING,
        allowNull: true,
    }

});

const NewsComment = sequelize.define('newsComments', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    comment: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    newsId: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    userName: {
        type: DataTypes.STRING,
        allowNull: false,
    }
});

async function initNews() {
    await News.sync();
    await NewsComment.sync();
    const count = await News.count();
    if (0 === count) {
        const newJson = [
            {
                title: 'Somalia, UN warn of worsening drought',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/dcac912057219a23056cd902ccbac88d.jpg',
            },
            {
                title: 'Russia records 8,702 new COVID-19 cases',
                content: 'Russia confirmed 8,702 new coronavirus infections over the past 24 hours, taking the nationwide tally to 4,641,390, the official monitoring and respons',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/fee1f0f1e66447027b651208d6dcd277.jpg',
            },
            {
                title: 'Xinhua Commentary: Rampant gun violence makes U.S.',
                content: 'A recent string of mass shootings in the United States have once again proved that the country, always proclaiming itself a defender of human right',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/0a75d71152a4552d50aa553bcc031f41.jpg',
            },
            {
                title: 'Philippines receives more Sinovac vaccines purchased from China',
                content: 'The Philippines on Sunday received the second batch of Sinovac Biotechs CoronaVac vaccines purchased from China.The Philippine Airlines',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/eb7d4e963cd2f588b58fefceb61165bf.jpg',
            },
            {
                title: 'Diesel trains manufactured by China put into operation in Malaysia',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/66a92a41bf4c9ab8c33444e9faf6d56a.jpg',
            },
            {
                title: '8 rescued, 21 trapped in coal mine accident in Xinjiang',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/b028f3bced9ccf8e7fffe4a1cbcd9220.jpg',
            },
            {
                title: 'Chinese president and wife send condolences over death of Britains Prince Philip',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/5edf5e69bd22ecde6625fd685b388999.jpg',
            },
            {
                title: 'UK records another 2,589 coronavirus cases, 40 deaths',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/572517b5e658f22030a7afa69c97b036.jpg',
            },
            {
                title: 'Claims about Russia, China waging "vaccine war" regrettable: Russian FM',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/c041e325fa758344d277e32f8810fd21.jpg',
            },
            {
                title: 'NYS COVID-19 hospitalizations down to 4,241, positivity rate 2.79 pct: governor',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/2259a4b72d9bea7f51d2e6daabe877ff.jpg',
            },
            {
                title: 'Turkish president calls for peaceful, diplomatic solution to tensions in eastern Ukraine',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/04/2c99159c8fa765c7c9d81b2f1a898b35.jpg',
            },
            {
                title: 'China willing to work with Brazil to promote comprehensive strategic partnership: Chinese FM',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/5f1c7731832ad67064f3a903224fae6e.jpg',
            },
            {
                title: 'Feature: Dedication ceremony honours unique Chinese-Maori bond',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/e6286712450fece92afa02da1656560f.jpg',
            },
            {
                title: 'COVID-19 variants spread leads to surge of new cases in Canada',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/e367e4bade5d6446f7e57ee395cfe74e.jpg',
            },
            {
                title: 'Indias states flag COVID-19 vaccine shortage',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/bcbccbb039fb922761cdb84f89b03705.jpg',
            },
            {
                title: 'Chinese FM urges continuity, stability of China-EU relations',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/bf11c8b3de93ea0e92d09ee838a7e66b.jpg',
            },
            {
                title: 'Chinese envoy urges U.S. to immediately lift unilateral sanctions',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/9f2beb3f2b79af29149d80052dbbe75c.jpg',
            },
            {
                title: 'China urges Japan to thoroughly assess radioactive water disposal plan',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/22a330d8cfc40e2de50d02b9ab7a0ff6.jpg',
            },
            {
                title: 'Pakistan approves Chinas Sinovac COVID-19 vaccine for emergency use',
                content: 'This is test news content',
                type: 0,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/3f46e8260a4b7491f22cde905a2cd055.jpg',
            },
            {
                title: 'Feature: Science fiction inspires entrepreneur to bridge language gap',
                content: 'This is test news content',
                type: 1,
                commentNumber: 0,
                img: 'http://www.hxen.com/d/file/p/2021/03/a3fd2d0c905c66007771fa30a25916c8.jpg',
            },
        ];
        await News.bulkCreate(newJson);

        console.log('初始化新闻成功！');
    }
}
initNews();




const newsModel = {
    async getNews(ctx) {
        const params = ctx.query;
        // const count = await News.count();
        const { offset = 0, limit = 10, keywords = '', type = 0 } = params;

        const info = await News.findAndCountAll(
            {
                where: {
                    title: {
                        [Op.like]: '%' + (keywords || '') + '%',
                    },
                    type: type,
                },
                limit: parseInt(limit),
                offset: parseInt(offset),
                raw: true,
            }
        );

        const user = await User.findOne({
            where: {
                id: ctx.session.sessionData.id,
            },
            raw: true,
        });
        const historyNews = user.historyNews ? user.historyNews.split(',') : [];

        info.rows.forEach(news => {
            if (-1 !== historyNews.indexOf(news.id)) {
                news.isHistory = true;
            } else {
                news.isHistory = false;
            }
        });


        ctx.pageRes({
            limit,
            offset,
            list: info.rows,
            total: info.count,
        });
    },
    async comment(ctx) {
        const params = ctx.request.body;
        if (!params.comment) {
            ctx.errorParams('请输入评论内容！');
            return;
        } else if (!params.newsId) {
            ctx.errorParams('没传新闻id！');
            return;
        }
        const news = await News.findOne({
            where: {
                id: params.newsId,
            },
            raw: true,
        });
        if (!news) {
            ctx.errorParams('新闻id有问题哟！');
            return;
        }

        const comment = await NewsComment.create({
            ...params,
            userName: ctx.session.sessionData.nickName,
        });
        news.commentNumber += 1;

        await News.update({
            ...news,
        }, {
            where: {
                id: news.id
            },
        });

        ctx.success('评论成功！', comment);
    },
    async getComment(ctx) {
        const params = ctx.query;
        // const count = await Words.count();
        const { id } = params;
        if (!id) {
            ctx.errorParams('请传新闻id！');
            return;
        }
        const info = await NewsComment.findAll({
            where: {
                newsId: id,
            },
            raw: true,
        });

        ctx.success('查询成功！', info);
    },
    async pointNews(ctx) {
        const params = ctx.request.body;
        // const count = await Words.count();
        const {id} = params;
        if (!id) {
            ctx.errorParams('请传新闻id！');
            return ;
        }
        const info = await User.findOne({
            where: {
                id: ctx.session.sessionData.id,
            },
            raw: true,
        });
        console.log(ctx.session.sessionData);
        const historyNews = info.historyNews ? info.historyNews.split(',') : [];
        if (-1 === historyNews.indexOf(id)) {
            historyNews.push(id);
        }
        await User.update({
            ...info,
            historyNews: historyNews.join(),
        }, {
            where: {
                id: ctx.session.sessionData.id
            },
        });

        ctx.success('成功！');

    },
};


module.exports = {
    newsModel,
    News
};